package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._

object Demo1FlinkSql {
  def main(args: Array[String]): Unit = {

    //flink  流处理的环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置flink  sql 配置
    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() // 使用blink 的计划器（解析sql）
      .inStreamingMode()
      .build()

    //创建table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)

    /**
      * executeSql 可以执行创建表的语句，处理数据的语句
      *
      */

    /**
      * 读取数据: 创建source 表  --> 动态表
      *
      */
    bsTableEnv.executeSql(
      """
        |CREATE TABLE lines (
        | line String
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'lines',
        | 'properties.bootstrap.servers' = 'master:9092',
        | 'properties.group.id' = 'asdsadasd',
        | 'format' = 'csv',
        | 'scan.startup.mode' = 'earliest-offset',
        | 'csv.ignore-parse-errors' = 'true'
        |)
        |
      """.stripMargin)

    /**
      * 创建 mysql sink 表
      *
      * 需要先在mysql中创建表
      *
      */

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE words (
        |  line String,
        |  c bigint,
        |  PRIMARY KEY (line) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/test',
        |   'table-name' = 'word_count',
        |   'username' = 'root',
        |   'password' = '123456'
        |)
        |
      """.stripMargin)


    /**
      * 编写sql 实时处理数据
      * 实时统计单词的数量
      *
      */

    bsTableEnv.executeSql(
      """
        |insert into words
        |select line,count(1) c from
        |lines
        |group by line
        |
      """.stripMargin)


    //打印结果

    /* table.toRetractStream[Row].print()
     bsEnv.execute()*/

  }

}
